package com.nd.android.u.ui.chatUiUtils;

import ims.IMSdkEntry;
import ims.cmd.PersonNotifyCmd;

import java.util.ArrayList;
import java.util.Date;

import android.content.Context;
import android.text.SpannableString;
import android.text.TextUtils;

import com.common.android.utils.smiley.Smileyhelper;
import com.nd.android.u.controller.ChatConst;
import com.nd.android.u.controller.ChatConst.MessageContentType;
import com.nd.android.u.controller.bean.FontFormat;
import com.nd.android.u.controller.bean.ImageMessage;
import com.nd.android.u.controller.bean.message.BaseDisplayMessage;
import com.nd.android.u.controller.factory.ShareFileFactory;
import com.nd.android.u.controller.innerInterface.IShareFile;
import com.nd.android.u.controller.outInterface.IMessageAnalyser;
import com.nd.android.u.ui.ChatEntry;
import com.nd.android.u.ui.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.product.android.commonInterface.chat.ChatGroup;

/**
 * 字符串格式的聊天消息解析 <br>
 * Created 2014-5-27 下午5:43:48
 * 
 * @version
 * @author cb
 * @see
 */
public class StringMessageAnalyser implements IMessageAnalyser{

	private static final String FMGSTART = "<fmt>";
	private static final String FMTEND = "<fmt>";
	private static final String IMGSTART = "<img>";
	private static final String IMGEND = "<img>";

	/**
	 * 解析消息
	 * <br>Created 2014-5-28 下午9:58:27
	 * @param message
	 * @author       cb
	*/
	@Override
	public void analyseMessage(BaseDisplayMessage message) {
		if (message == null) {
			return;
		}
		/**系统公告的特殊处理*/
		if(message.groupType==ChatGroup.getUntidGroupType()){
		    String data=message.oriMessage;
           if (TextUtils.isEmpty(data)) {
                return;
            }
	        //拆分标题和内容
	        String[] datas =data.split(ChatConst.SPLITTITLE);
            if (data.length()>1){
                message.displayContent=datas[0];
            }else{
                message.displayContent=data;  
            }
		    return ;
		}
		Context context=IMSdkEntry.INSTANCE.context;
		switch (message.messageContentType) {
		case MessageContentType.TEXT:
		case MessageContentType.PICTURE:
		case PersonNotifyCmd.MSG_A2A_AUTO_REPLY:	//自动回复的消息
		case MessageContentType.MULTI_PICTURE:
			message.dataList.clear();
			String content = message.oriMessage;
			if (TextUtils.isEmpty(content)) {
				return;
			}
			analyseText(message,content);
			break;
		case MessageContentType.FILE:
		case MessageContentType.OLD_FILE:
			message.oriMessage=context.getString(R.string.chat_file);
			message.displayContent=message.oriMessage;
			break;
		case MessageContentType.AUDIO:
		case MessageContentType.OLD_AUDIO:
			message.oriMessage=context.getString(R.string.chat_audio);
			message.displayContent=message.oriMessage;
			break;
		case MessageContentType.VIDEO:
			message.oriMessage=context.getString(R.string.chat_vidio);
			message.displayContent=message.oriMessage;
			break;
		default:
			message.oriMessage=context.getString(R.string.chat_error_msg);
			message.displayContent=message.oriMessage;
			break;
		}
	}

	/**
	 * 解析消息文本
	 * <br>Created 2014-5-28 下午7:46:17
	 * @param message
	 * @param content
	 * @author       cb
	*/
	private void analyseText(BaseDisplayMessage message, String content) {
		// 示例："123 12 235&<img>*257:3:1026*257:6:1026<img>&&<fmt>4278190079:67108864:12:0:微软雅黑<fmt>&"
		String data = content.replace('\r', '\n');
		// 删除文字格式(如果用户自己输入这样的字符串就没办法了)
		int fmtStart = data.indexOf("&" + FMGSTART);
		int fmtEnd = data.indexOf(FMTEND + "&");
		if (fmtStart > -1 && fmtEnd > fmtStart) {
			data = data.substring(0, fmtStart);
		}
		String IMAGE_TEXT = IMSdkEntry.INSTANCE.context
				.getString(R.string.image_info);
		String imgStart = "&" + IMGSTART;
		String imgEnd = IMGEND + "&";
		StringBuffer finalData = new StringBuffer();
		ArrayList<Object> dataList = new ArrayList<Object>(); 
		if (data.indexOf(imgStart + imgEnd) > -1) {
			// 存在形如"&<img><img>&"这样的空图片字符串，即说明没有别的图片，直接删除(如果用户自己输入这样的字符串就没办法了)
			data = data.replace(imgStart + imgEnd, "");
			setDefaultData(message, data);
		} else {
			// 分解表情字符串
			int imgStartIndex = data.indexOf(imgStart);
			int imgEndIndex = data.indexOf(imgEnd);
			if (imgStartIndex > -1 && imgEndIndex > -1) {
				// 存在匹配的表情字符串
				// "123 12 235&<img>*257:3:1026*257:6:1026<img>&
				String[] dataArray = data.split(imgStart);
				// dataarray=[123 12 235,&<img>*257:3:1026*257:6:1026<img>&]
				int len = dataArray.length;
				if (len <= 1) {
					// 异常分支
					setDefaultData(message, data);
				} else {
					// textPart=123 12 235
					String textPart = dataArray[0];
					// imagePart=*257:3:1026*257:6:1026<img>&
					String imagePart = dataArray[1];
					String[] imageArray = imagePart.split("\\*");
					// imageArray=[,257:3:1026,257:6:1026<img>&]
					len = imageArray.length;
					if (len <= 1) {
						// 异常分支
						setDefaultData(message, data);
					} else {
						int subTextIndex = 0;
						for (int i = 1; i < len; i++) {
							// 分散诸如257:3:1026这样的字符串
							String imageText = imageArray[i];
							if (i == len - 1) {
								// 是最后一个数据项，把<img>&删除（比如257:6:1026<img>&）
								imageText = imageText.replace(imgEnd, "");
							}
							String[] imageDatas = imageText.split(":");
							int dataLen = imageDatas.length;
							if (dataLen <= 1) {
								// 异常分支
								setDefaultData(message, data);
								return;
							}
							try {
								int type = Integer.parseInt(imageDatas[0]);
								int position = Integer.parseInt(imageDatas[1]);
								if (position != 0) {
									// 第一个图不是起始位置，取第一段文字
									if (subTextIndex<position){
										String text = textPart.substring(subTextIndex, position);
										addStringToList(dataList, text, finalData);	
									}
								}
								subTextIndex = position + 1;
								if (type == 257) {
									int id = Integer.parseInt(imageDatas[2]);
									if (Smileyhelper.getInstance().isCatID(id)) {
										// 如果是猫表情，要显示动画
										ImageMessage imageMsg = new ImageMessage();
//										String generateid = message.getImageGenerateId(imageIndex);
										finalData.append(imgStart + imageDatas[2] + imgEnd);
										imageMsg.setPosition(position);
										imageMsg.setType(type);
										imageMsg.setImgurl(id + "");
										dataList.add(imageMsg);
										if (dataList.size()==1){
										    message.messageContentType=MessageContentType.PICTURE;
										}else{
										    message.messageContentType=MessageContentType.MULTI_PICTURE;
										}
									} else {
										// 如果是其它表情，直接转成表情表达式
										addStringToList(dataList,
												imgStart + imageDatas[2] + imgEnd, finalData);
									}
									continue;
								}
								// 非表情，构造imagemessage
								ImageMessage imageMsg = new ImageMessage();
//								String generateid = message.getImageGenerateId(imageIndex);
								imageMsg.setImgurl(imageDatas[2]);
								int contentType=MessageContentType.PICTURE;
								IShareFile shareFile=ShareFileFactory.INSTANCE.getShareFileInterface(IShareFile.DOWNLOAD, contentType);
						        String url=shareFile.getShareFileUrl(imageDatas[2], "", contentType);
								// 获取图片下载后存放的路径
								String path = ImageLoader.getInstance().getDiscCacheFileAbsPath(
										ChatEntry.INSTANCE.chatOptions, url);
								imageMsg.setPosition(position);
								imageMsg.setType(type);
								imageMsg.text = IMAGE_TEXT;
								finalData.append(IMAGE_TEXT);
								if (dataList.size()>0){
								    message.messageContentType=MessageContentType.MULTI_PICTURE;
								    message.url=null;
								}else{
								    message.messageContentType=MessageContentType.PICTURE;
								    message.url=url;
								}
								dataList.add(imageMsg);
							} catch (Exception e) {
								setDefaultData(message, data);
								return;
							}
						}
						if (subTextIndex < textPart.length()) {
							String lastText = textPart.substring(subTextIndex);
							addStringToList(dataList, lastText, finalData);
						}
						message.displayContent=finalData.toString();
						if (dataList.size()>1){
							if (message.messageContentType==MessageContentType.PICTURE){
								message.messageContentType=MessageContentType.MULTI_PICTURE;
							}
						}
						message.dataList.addAll(dataList);
					}
				}
			} else {
				// 不存在表情字符(实际上这个处理在上面替换空图片字符串时已经排除了，但是不知道以后规则会不会变，所以还是加上）
				setDefaultData(message, data);
			}
		}
	}
	
	

	/**
	 * 设置默认值
	 * <br>Created 2014-5-28 下午7:46:31
	 * @param message
	 * @param data
	 * @author       cb
	*/
	private void setDefaultData(BaseDisplayMessage message, String data) {
		message.displayContent = data;
		message.dataList.add(data);
	}

	/**
	 * @n<b>函数名称</b> :addStringToList
	 * @brief 把字符串添加到dataList里面
	 * @see
	 * @since Ver 1.3.x
	 * @param @param list 目标数组
	 * @param @param data 欲添加的文本
	 * @param @param finalText 最终的文本
	 * @return void
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-11-27下午9:41:26
	 */
	private void addStringToList(ArrayList<Object> list, String data, StringBuffer finalText) {
		finalText.append(data);
		int size = list.size();
		if (size == 0) {
			// 没有数据
			list.add(data);
		} else {
			Object obj = list.get(size - 1);
			if (obj instanceof String) {
				// 上一个数据项也是字符串，合并
				list.set(size - 1, ((String) obj) + data);
			} else {
				// 上一个数据项不是字符串，新增
				list.add(data);
			}
		}
	}
	
	/**
	 * 打包消息（要把消息打包成服务端能识别的格式）
	 * <br>Created 2014-5-28 下午9:59:14
	 * @param msg
	 * @return
	 * @author       cb
	*/
	@Override
	public String packMsg(BaseDisplayMessage msg){
		StringBuffer bufferText=new StringBuffer();
		StringBuffer bufferImage=new StringBuffer();
		String imgStart="&"+IMGSTART;
		String imgEnd=IMGEND+"&";
		bufferImage.append(imgStart);
		ArrayList<Object> datas=msg.getDisplayDatas();
		if (datas.isEmpty()){
			packString(msg.displayContent,bufferText,bufferImage);
		}else{
			for (int i=0,len=datas.size();i<len;i++){
				Object obj=datas.get(i);
				if (obj instanceof String){
					packString((String) obj,bufferText,bufferImage);
				}else if (obj instanceof ImageMessage){
					bufferImage.append("*"+((ImageMessage) obj).getType()+":"+bufferText.length()+":"+((ImageMessage) obj).getImgurl());
					bufferText.append(" ");
				}else if (obj instanceof SpannableString){
					packString(obj.toString(),bufferText,bufferImage);
				}
			}
		}
		bufferImage.append(imgEnd);
		return bufferText.toString()+bufferImage.toString()+FontFormat.getString();
	}
	
	/**
	 * 打包某个字符串
	 * <br>Created 2014-5-28 下午10:04:27
	 * @param text
	 * @param textString
	 * @param imageString
	 * @author       cb
	*/
	public static void packString(String text,StringBuffer textString,StringBuffer imageString){
		String imgStart="&"+IMGSTART;
		String imgEnd=IMGEND+"&";
		int type=257;
		if (text.indexOf(imgEnd)>-1 && text.indexOf(imgStart)>-1){
			//可能存在表情
			String[] datas=text.split(imgStart);
			int len=datas.length;
			if (len<=1){
				textString.append(text);
			}else{
				for (int i=0;i<len;i++){
					String data=datas[i];
					if (!TextUtils.isEmpty(data)){
						if (data.indexOf(imgEnd)>-1){
							//属于表情
							String[] endParts=data.split(imgEnd);
							if (endParts.length>1){
								imageString.append("*"+type+":"+textString.length()+":"+endParts[0]);
								textString.append(" "+endParts[1]);
							}else{
								imageString.append("*"+type+":"+textString.length()+":"+endParts[0]);
								textString.append(" ");
							}
						}else{
							textString.append(data);	
						}
					}
				}
			}
		}else{
			textString.append(text);
		}
	}

    @Override
    public String createDate(BaseDisplayMessage msg) {
        // 自定义时间格式
    	
    	return ChatTimeUtils.parseDate(new Date(msg.createDate* ChatConst.MILLI * 1L), 1);
//        return StarAppUtils.getSpecialShowTimeMS((msg.createDate)* ChatConst.MILLI * 1L);
    }
}
